package wubj.com.floatwindow.activity;

import android.annotation.TargetApi;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import java.util.List;

import wubj.com.floatwindow.FloatWindowService;
import wubj.com.floatwindow.R;
import wubj.com.floatwindow.utils.ToastU;

@TargetApi(Build.VERSION_CODES.M)
public class MainActivity extends AppCompatActivity {

    private Context mContext;

    public static int OVERLAY_PERMISSION_REQ_CODE = 1234;
    public static int ACTION_USAGE_PERMISSION_REQ_COD = 1314;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_main);
        Button start = (Button) findViewById(R.id.start_float_window);
        Button startSearch = (Button) findViewById(R.id.start_search);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestDrawOverLays();
            }
        });
        startSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(mContext, SearchActivity.class));
            }
        });
//        requestUsageStats();
    }

    private void start() {
        Intent intent = new Intent(mContext, FloatWindowService.class);
        startService(intent);
        finish();
    }

    public void requestDrawOverLays() {
        if (!Settings.canDrawOverlays(MainActivity.this)) {
            ToastU.showSingleS("没有在其他应用上层显示的权限");
            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + MainActivity
                    .this.getPackageName()));
            startActivityForResult(intent, OVERLAY_PERMISSION_REQ_CODE);
        } else {
            // Already hold the SYSTEM_ALERT_WINDOW permission, do addview or something.
//            start();
            requestUsageStats();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == OVERLAY_PERMISSION_REQ_CODE) {
            if (!Settings.canDrawOverlays(this)) {
                ToastU.showSingleS("获取权限时被拒绝,功能无法使用");
            } else {
                ToastU.showSingleS("获取权限成功");
//                start();
                requestUsageStats();
            }
        } else if (requestCode == ACTION_USAGE_PERMISSION_REQ_COD) {
            if (!isSwitch()) {
                ToastU.showSingleS("获取权限时被拒绝,部分功能无法使用");
            } else {
                ToastU.showSingleS("获取权限成功");
                start();
            }
        }
    }

    private void requestUsageStats() {
        if (!isSwitch()) {
            ToastU.showSingleS("该App无权查看应用的使用权限");
            Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
            startActivityForResult(intent, ACTION_USAGE_PERMISSION_REQ_COD);
        } else {
            start();
        }
    }

    private boolean isNoOption() {
        PackageManager packageManager = getApplicationContext().getPackageManager();
        Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
        List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return list.size() > 0;
    }

    private boolean isSwitch() {
        long ts = System.currentTimeMillis();
        UsageStatsManager usageStatsManager = (UsageStatsManager) getApplicationContext().
                getSystemService(Context.USAGE_STATS_SERVICE);
        List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, 0, ts);
        if (queryUsageStats == null || queryUsageStats.isEmpty()) {
            return false;
        }
        return true;
    }

}
